package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    private final StringRedisTemplate stringRedisTemplate;
    private static final long startTime = 1735660800L;// 2025/1/1时间戳，以秒为单位
    RedisIdWorker(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public  long nextId(String keyPrefix){
        //生成时间戳
        ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.of("Asia/Shanghai"));
        long endTime = now.toEpochSecond();
        long timeStamp = (endTime - startTime) << 32;
        //生成序列号，使用INCR命令得到
        String today = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + today);
        long id = timeStamp | count;
        return id;
    }
}
